package com.bw.permission.controller;


import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import com.bw.permission.config.AjaxResult;
import com.bw.permission.utils.WebUtils;
import com.bw.springboot.starter.upload.service.FileService;
import com.bw.springboot.starter.upload.util.FileResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

@RestController
@RequestMapping("/file/")
public class UploadController {

    @Autowired
    private FileService fileService;

    @RequestMapping("upload")
    public AjaxResult upload(MultipartFile file){

        FileResult upload = null;
        try {
            upload = fileService.upload(file);
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.err(10000,"文件上传失败");
        }
        return AjaxResult.ok(upload);
    }

    @Value("${file.path}")
    private String filePath;

    @GetMapping("download")
    public void download(String id) throws IOException {
        HttpServletResponse response = WebUtils.getResponse();
        String fileName = "pdf-"+id+".pdf";
//        fileName = new String(fileName.getBytes("UTF-8"),"ISO8859-1");
        File pdfFile = new File(filePath+fileName);
        byte[] bytes = FileUtil.readBytes(pdfFile);
        //设置返回内容格式
        ServletOutputStream outputStream = response.getOutputStream();
        //设置返回内容格式
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        //返回数据到输出流对象中
        outputStream.write(bytes);
        IoUtil.close(outputStream);
    }


}
